

import os
import time
import logging
import multiprocessing as mp

import rpyc
from rpyc.utils import server

import dexen
from dexen.system import node
from dexen.system.node.master import master
from dexen.system.node.slave import slave
from dexen.system.base import service

#===============================================================================
# Globals
#===============================================================================
masters = {}
slaves = {}

#===============================================================================
# Service
#===============================================================================
class NodeService(dexen.Service):
        
    def create_master(self, master_name):
        logging.debug("I am creating master %s", master_name)
        proc = mp.Process(target=master.start, name=master_name, 
                          args=(master_name, name)) 
        masters[master_name] = proc
        proc.start()
        logging.debug("Master %d is started", proc.pid)
        time.sleep(0.1)
        
    def create_slave(self, master_name, slave_name):
        proc = mp.Process(target=slave.start, name=slave_name, 
                          args=(master_name, slave_name, name)) 
        slaves[slave_name] = proc
        proc.start()
        time.sleep(0.1)
            
    def test(self):
        "I am in agent testing"
#===============================================================================
# Main
#===============================================================================
def main():
    global start_time, name
    print "I am in main"
    logging.basicConfig(level=logging.DEBUG)
    
    if not os.path.exists(node.TEMP_DIR):
        os.mkdir(node.TEMP_DIR)

    start_time = time.time()
    
    conn = rpyc.connect_by_service(service_name="NODEREGISTRY")
    name = conn.root.register(start_time)

    NodeService.ALIASES = [name]
    svr = server.ThreadedServer(NodeService, 
                                protocol_config=service.default_config)
    svr.start()

if __name__ == "__main__":
    main()
    
